package com.test.qrcode.manage.controller;

import com.test.qrcode.manage.model.entity.User;
import com.test.qrcode.manage.response.Response;
import com.test.qrcode.manage.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * @program qrcode
 * @Title: UserController
 * @description: 对用户资源的增删改查
 * @author: XueXiao
 * @create: 2019-02-27 17:57:56
 */

@RestController
public class UserController {

    private UserService userService;
    
    private static final Logger log = Logger.getLogger(UserController.class);

    public UserService getUserService() {
        return userService;
    }

    @Resource(name = "userService")
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /** 
    * @Description: 根据Id查询用户
    * @Author: XueXiao 
    * @Date: 2019/2/28 10:00
    */ 
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Object getUser(@PathVariable("id") long id) {
        User user = (User) userService.findUserById(id);
        log.debug("查询用户 :" + user);
        Response response = new Response().success(user);
        return response;
    }

    /** 
    * @Description: 查询所有用户
    * @Author: XueXiao 
    * @Date: 2019/2/28 17:49
    */ 
    @RequestMapping(value = "/user/", method = RequestMethod.GET)
    public Object getUsers(){
        log.debug("查询所有用户");
        List<User> users = userService.findAllUsers();
        Response response = new Response().success(users);
        return response;
    }

    /** 
    * @Description: 添加用户
    * @Author: XueXiao 
    * @Date: 2019/2/28 10:07
    */ 
    @RequestMapping(value = "/user/", method = RequestMethod.POST, produces = "application/json",
            consumes = "application/json")
    public Object addUser(@RequestBody @Valid User user) {
        userService.addUser(user);
        log.debug("添加用户 :" + user);
        Response response = new Response().success(user);
        return response;
    }
    
    /** 
    * @Description: 更新用户
    * @Author: XueXiao 
    * @Date: 2019/2/28 17:52
    */ 
    @RequestMapping(value = "/user/", method = RequestMethod.PUT, produces = "application/json",
            consumes = "application/json")
    public Object updateUser(@RequestBody @Valid User user){
        log.debug("更新用户 :" + user);
        userService.updateUser(user);
        Response response = new Response().success(user);
        return response;
    }
    /** 
    * @Description: 根据ID删除用户
    * @Author: XueXiao 
    * @Date: 2019/3/1 08:51
    */ 
    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public Object deteteUser(@PathVariable("id") long id){
        log.debug("删除Id为" + id + "的用户");
        userService.deleteUserById(id);
        return new Response().success();
    }
}
